package cn.com.cifi.mars.service.impl;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.bo.PortalTodoBo;
import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.dto.PriceValueCollectDto;
import cn.com.cifi.mars.bean.dto.ProjectOrgDto;
import cn.com.cifi.mars.bean.dto.SupplyPlanVersionDto;
import cn.com.cifi.mars.bean.vo.supply.SupplyPlanVersionsVO;
import cn.com.cifi.mars.bean.vo.sys.rsp.GroupUserVo;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.BudgetCycleEnum;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.IsDelayEnum;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.constant.IsSuccessEnum;
import cn.com.cifi.mars.constant.LogEventEnum;
import cn.com.cifi.mars.constant.LogSrcEnum;
import cn.com.cifi.mars.constant.LogTypeEnum;
import cn.com.cifi.mars.constant.ModifySourceTypeEunm;
import cn.com.cifi.mars.constant.ModuleTypeEunm;
import cn.com.cifi.mars.constant.OperatorTypeEnum;
import cn.com.cifi.mars.constant.OrgTypeEunm;
import cn.com.cifi.mars.constant.SalyTypeEnum;
import cn.com.cifi.mars.constant.StageStatusEnum;
import cn.com.cifi.mars.constant.SupplyConfirmCodeEnum;
import cn.com.cifi.mars.constant.SupplyConfirmStatusEnum;
import cn.com.cifi.mars.constant.TodoOrgTypeEnum;
import cn.com.cifi.mars.constant.TodoStatusEnum;
import cn.com.cifi.mars.constant.TodoTypeCodeEnum;
import cn.com.cifi.mars.constant.VersionAttrEnum;
import cn.com.cifi.mars.constant.VersionEventEnum;
import cn.com.cifi.mars.constant.VersionIdTypeEnum;
import cn.com.cifi.mars.constant.VersionIdentifyEnum;
import cn.com.cifi.mars.constant.VersionStatusEnum;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.constant.isAssessmentVersionEnum;
import cn.com.cifi.mars.entity.MdmStage;
import cn.com.cifi.mars.entity.PriceVersion;
import cn.com.cifi.mars.entity.SupplyPlanVersion;
import cn.com.cifi.mars.entity.SupplyPlanVersionDetail;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.entity.common.ProjectByStages;
import cn.com.cifi.mars.entity.common.SysDictionary;
import cn.com.cifi.mars.mapper.mars.ProjectMapper;
import cn.com.cifi.mars.mapper.mars.SupplyPlanVersionDetailMapper;
import cn.com.cifi.mars.mapper.mars.SupplyPlanVersionMapper;
import cn.com.cifi.mars.service.CommonService;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.SignPlanVersionService;
import cn.com.cifi.mars.service.StageService;
import cn.com.cifi.mars.service.SupplyConfirmRecordDetailService;
import cn.com.cifi.mars.service.SupplyPlanVersionService;
import cn.com.cifi.mars.service.SysDictionaryService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.service.VersionLogService;
import cn.com.cifi.mars.util.DateUtils;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.StrUtils;
import cn.com.cifi.mars.util.UUIDUtils;
import cn.com.cifi.mars.util.VersionUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 供货计划版本表 服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-09
 */
@Slf4j
@Service
public class SupplyPlanVersionServiceImpl extends ServiceImpl<SupplyPlanVersionMapper, SupplyPlanVersion>
		implements SupplyPlanVersionService {

	@Autowired
	private SupplyPlanVersionMapper supplyPlanVersionMapper;

	@Autowired
	private SupplyPlanVersionDetailMapper supplyPlanVersionDetailMapper;

	@Autowired
	private ProjectMapper projectMapper;

	@Autowired
	private SignPlanVersionService signPlanVersionService;

	@Autowired
	private IdmUserService idmUserService;

	@Autowired
	private CommonService commonService;

	@Autowired
	private SysDictionaryService sysDictionaryService;

	@Autowired
	private SysLogService sysLogService;

	@Autowired
	private VersionLogService versionLogService;

	@Autowired
	private StageService stageService;

	@Autowired
	private SupplyConfirmRecordDetailService supplyConfirmRecordDetailService;

	@Value("${confirm_todo_url}")
	private  String confirmTodoUrl;

	@Value("${PORTAL_SYSCODE}")
	private String systemCode;

	@Value("${mobile_task_url}")
	private String  mobileTaskUrl;

	private static final String YEAR_MONTH_DAY="yyyy-MM-dd";

	@Override
	public List<SupplyPlanVersionsVO> queryVersions(String projectFId, String versionType) {
		return supplyPlanVersionMapper.selectVersions(projectFId, versionType, IsDeleteEnum.NO.getKey());
	}

	@Override
	public List<SupplyPlanVersion> queryNewestVersionByProjectId(String projectId,String stageName) {
		return supplyPlanVersionMapper.selectNewestVersionByProjectId(projectId,stageName,IsDeleteEnum.NO.getKey());
	}

	@Override
	public String queryVersionType(String versionId) {
		return supplyPlanVersionMapper.selectVersionType(versionId,IsDeleteEnum.NO.getKey());
	}

	@Override
	public String queryNewestVersionStage(String projectFid) {
		return supplyPlanVersionMapper.selectNewestVersionStage(projectFid,IsDeleteEnum.NO.getKey());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public synchronized void createSupplyPlanVersion(String priceVersionId, String versionType, String userName) {
		log.info("###############创建供货计划版本   Start: "+ LocalDateTime.now());
		PriceVersion priceVersion = supplyPlanVersionMapper.selectPriceVersion(priceVersionId, IsDeleteEnum.NO.getKey());
		String logContent = "";
		if(priceVersion == null) {
			logContent = "货值版本不存在或已删除，货值版本ID："+priceVersionId ;
			saveLog("供货计划","创建供货计划版本失败",logContent,IsSuccessEnum.FAIL.getKey());
			return;
		}else {
			try {
				String projectId = priceVersion.getProjectId();
				String stageId = priceVersion.getProjectfId();
				//归属月份(已货值为准)
				String affiliationMonth  = "";
				if(priceVersion.getAscriptionDate() != null) {
					affiliationMonth  = LocalDateTimeUtils.formatDate(priceVersion.getAscriptionDate(),"yyyy-MM");
				}else {
					affiliationMonth  = LocalDateTimeUtils.formatTime(priceVersion.getCreateTime(),"yyyy-MM");
				}
				//版本号
				String versionNum = "";
				String supplyPlanVersionId = "";
				String beforeState = "";
				String afterState = "";
				String event = VersionEventEnum.SYS_GENERATE.getKey();
				Integer isAssessmentVersion = priceVersion.getIsAssessmentVersion();

				List<PriceValueCollectDto> priceValueList = supplyPlanVersionDetailMapper.selectPriceValueOrgCollect(priceVersionId,IsDeleteEnum.NO.getKey());
				if(CollectionUtils.isEmpty(priceValueList)) {
					logContent = "当前货值版本没有对应的版本详情，货值版本ID："+priceVersionId ;
					saveLog("供货计划","创建供货计划版本失败",logContent,IsSuccessEnum.FAIL.getKey());
					return;
				}

				if(versionType.equals(VersionTypeEunm.GETPRICE.getKey())) {
					versionType = VersionTypeEunm.DYNAMIC.getKey();
				}

				SupplyPlanVersion newestVersion = supplyPlanVersionMapper.selectNewestVersion(priceVersion.getProjectfId(),versionType,IsDeleteEnum.NO.getKey());

				/**
				 * 投资版生成规则：
				 * 	货值版本审批通过生成新版本
				 * 战规版生成规则：
				 * 	货值版本审批通过生成新版本
				 * 动态版生成刷新规则：
				 * 1、分期不存在当月月度动态版供货计划，生成新版本；
				 * 2、分期已存在当月月度动态版供货计划，
				 * 	一）已定稿，生成新版本；
				 * 	二）未定稿，比较新版货值与当月最新月度动态版供货计划的产品楼栋是否一致或计划日期是否一致：
				 * 	 1）不一致，生成新版本；
				 *   2）一致时，判断是否被签约使用
				 1）已使用，生成新版本；
				 2）未使用，是否已确认供货；
				 1）已确认，生成新版本
				 2）未确认，刷新实际数据

				 */
				if (versionType.equals(VersionTypeEunm.DYNAMIC.getKey()) || versionType.equals(VersionTypeEunm.GETPRICE.getKey())) {
					//当前分期最新预算版数据（判断是否延迟供货标识）
					List<SupplyPlanVersionDetail> newestBudgetDetailList = supplyPlanVersionDetailMapper.selectNewestBudgetDetailList(stageId,IsDeleteEnum.NO.getKey());
					if (newestVersion == null) {
						versionNum = VersionUtils.bigVersionInc("");
						priceValueList = handlePriceValue(priceValueList);
						//处理延迟供货标识
						handleIsDelay(newestBudgetDetailList,priceValueList);
						supplyPlanVersionId = saveSupplyPlanVersion(newestVersion,versionType, userName, priceVersion,affiliationMonth,versionNum);
						supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
						afterState = VersionStatusEnum.SYSGENERATION.getKey();
						logContent= "分期不存在当月月度动态版供货计划版本，生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
					} else {
						//目前最新版本已定稿
						if(isFinalizeVersion(newestVersion)) {
							if(newestVersion.getAffiliationMonth().equals(affiliationMonth)) {
								versionNum = VersionUtils.bigVersionInc(newestVersion.getVersionNum());
							}else {
								versionNum = VersionUtils.bigVersionInc("");
								newestVersion = null;
							}
							priceValueList = handlePriceValue(priceValueList);
							//处理延迟供货标识
							handleIsDelay(newestBudgetDetailList,priceValueList);
							supplyPlanVersionId = saveSupplyPlanVersion(newestVersion, versionType, userName, priceVersion,affiliationMonth,versionNum);
							supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
							afterState = VersionStatusEnum.SYSGENERATION.getKey();
							logContent= "最新供货计划版本已定稿，生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
						}else {
							List<SupplyPlanVersionDetail> supplyPlanValueOrgList = supplyPlanVersionDetailMapper.selectByVersionId(newestVersion.getId(), IsDeleteEnum.NO.getKey());
							//数据层级是否相同
							if (compareData(supplyPlanValueOrgList,priceValueList)) {
								//签约是否有编排计划（有-生产新版本；无-只刷新数据）
								boolean flag = signPlanVersionService.supplyBoolean(newestVersion.getId());
								if(flag) {
									if(newestVersion.getAffiliationMonth().equals(affiliationMonth)) {
										versionNum = VersionUtils.bigVersionInc(newestVersion.getVersionNum());
									}else {
										versionNum = VersionUtils.bigVersionInc("");
										newestVersion = null;
									}
									priceValueList = handlePriceValue(priceValueList);
									//处理延迟供货标识
									handleIsDelay(newestBudgetDetailList,priceValueList);
									supplyPlanVersionId = saveSupplyPlanVersion(newestVersion, versionType, userName, priceVersion,affiliationMonth,versionNum);
									supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
									afterState = VersionStatusEnum.SYSGENERATION.getKey();
									logContent= "产品楼栋一致、供货计划日期没变，已编排签约计划，生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
								}else {
									//是否确认供货（有-生产新版本；无-只刷新数据）
									if(isConfirmSupply(newestVersion)) {
										if(newestVersion.getAffiliationMonth().equals(affiliationMonth)) {
											versionNum = VersionUtils.bigVersionInc(newestVersion.getVersionNum());
										}else {
											versionNum = VersionUtils.bigVersionInc("");
											newestVersion = null;
										}
										priceValueList = handlePriceValue(priceValueList);
										//处理延迟供货标识
										handleIsDelay(newestBudgetDetailList,priceValueList);
										supplyPlanVersionId = saveSupplyPlanVersion(newestVersion, versionType, userName, priceVersion,affiliationMonth,versionNum);
										supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
										afterState = VersionStatusEnum.SYSGENERATION.getKey();
										logContent= "产品楼栋一致、供货计划日期没变，未编排签约计划，已确认供货，生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
									}else {
										if(newestVersion.getAffiliationMonth().equals(affiliationMonth)) {
											priceValueList = handlePriceValue(priceValueList);
											//处理延迟供货标识
											handleIsDelay(newestBudgetDetailList,priceValueList);
											//修改供货实际数据
											updateVersionData(newestVersion,priceValueList);
											//变更版本信息
											updateVersion(priceVersion, newestVersion);

											supplyPlanVersionId = newestVersion.getId();
											versionNum = newestVersion.getVersionNum();
											beforeState = VersionStatusEnum.SYSGENERATION.getKey();
											afterState = VersionStatusEnum.SYSGENERATION.getKey();;
											event = VersionEventEnum.SYS_REFRESH.getKey();
											logContent= "产品楼栋一致、供货计划日期没变，没有编排签约计划，没有确认供货，刷新版本数据，基于货值版本ID："+priceVersionId+"，刷新供货计划版本ID："+ newestVersion.getId();
										}else {
											versionNum = VersionUtils.bigVersionInc("");
											newestVersion = null;

											priceValueList = handlePriceValue(priceValueList);
											//处理延迟供货标识
											handleIsDelay(newestBudgetDetailList,priceValueList);
											supplyPlanVersionId = saveSupplyPlanVersion(newestVersion, versionType, userName, priceVersion,affiliationMonth,versionNum);
											supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
											afterState = VersionStatusEnum.SYSGENERATION.getKey();
											logContent= "产品楼栋一致、供货计划日期没变，未编排签约计划，没有确认供货，月份不同，生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
										}
									}
								}
							} else {
								if(newestVersion.getAffiliationMonth().equals(affiliationMonth)) {
									versionNum = VersionUtils.bigVersionInc(newestVersion.getVersionNum());
								}else {
									versionNum = VersionUtils.bigVersionInc("");
									newestVersion = null;
								}
								priceValueList = handlePriceValue(priceValueList);
								//处理延迟供货标识
								handleIsDelay(newestBudgetDetailList,priceValueList);
								supplyPlanVersionId = saveSupplyPlanVersion(newestVersion, versionType, userName, priceVersion,affiliationMonth,versionNum);
								supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
								afterState = VersionStatusEnum.SYSGENERATION.getKey();
								logContent= "产品楼栋不一致或计划日期变动，生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
							}
						}
					}

					try {
						//刷新确认供货表
						supplyConfirmRecordDetailService.initSupplyConfirmReport(affiliationMonth,projectId);
					} catch (Exception e) {
						log.error("######刷新确认供货表 errorMsg: ", e.getMessage());
						saveLog("供货计划","刷新确认供货表失败",e.getMessage(),IsSuccessEnum.FAIL.getKey());
					}

				} else {
					versionNum = VersionUtils.bigVersionInc(newestVersion==null?"":newestVersion.getVersionNum());
					priceValueList = handlePriceValue(priceValueList);
					supplyPlanVersionId = saveSupplyPlanVersion(newestVersion, versionType, userName, priceVersion,null,versionNum);
					supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);

					try {
						if(isValidSupplyPlanVersion(supplyPlanVersionId)) {
							//发送签约待办
							signPlanVersionService.signNoticeDispose(supplyPlanVersionId);
						}
					} catch (Exception e) {
						log.error("######发送签约待办 errorMsg: ",e.getMessage(), e);
					}
					afterState = VersionStatusEnum.SYSGENERATION.getKey();
					logContent= VersionTypeEunm.getValueByKey(versionType)+"生成新版本，基于货值版本ID："+priceVersionId+"，生成供货计划版本ID："+supplyPlanVersionId;
				}

				String versionName = prepareVersionName(versionType,versionNum,isAssessmentVersion,affiliationMonth,"","");

				versionLogService.saveVersionLogInfo(projectId,stageId,ModuleTypeEunm.SUPPLY_PLAN.getKey(),
						event,supplyPlanVersionId,versionName,
						beforeState,afterState,ModifySourceTypeEunm.TWO.getKey(),
						priceVersion.getId(),Constants.SYS,LocalDateTime.now(),"创建或刷新供货计划版本",logContent,IsDeleteEnum.NO.getKey(),Constants.SYS,LocalDateTime.now());

				saveLog("供货计划","创建供货计划版本",logContent,IsSuccessEnum.SUCCESS.getKey());
			} catch (Exception e) {
				log.error("######创建供货计划版本 errorMsg: ",e.getMessage(), e);
				saveLog("供货计划","创建供货计划版本失败","分期ID："+priceVersion.getProjectfId()+",错误信息："+e.getMessage(),IsSuccessEnum.FAIL.getKey());
			}
		}
		log.info("###############创建供货计划版本   End: "+ LocalDateTime.now());
	}

	private String prepareVersionName(String versionType,String vesionNum,
									  Integer isAssessmentVersion,String affiliationMonth,String budgetYear,String versionIdentify) {
		String versionName="";
		String versionTypeName = VersionTypeEunm.getValueByKey(versionType);
		String lastDate = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMdd");
		if(versionType.equals(VersionTypeEunm.INVESTMENT.getKey()) || versionType.equals(VersionTypeEunm.WARPLAN.getKey())) {
			String assessmentTag="";
			if(isAssessmentVersion != null && isAssessmentVersion.intValue() == 1) {
				assessmentTag = "(考核版)";
			}
			versionName = versionTypeName+vesionNum+"-"+lastDate+assessmentTag;
		}else if(versionType.equals(VersionTypeEunm.BUDGET.getKey())) {
			String versionIdentifyName = VersionIdentifyEnum.getValueByKey(versionIdentify);
			versionName = budgetYear+versionIdentifyName+"预算版"+vesionNum+"-"+lastDate;
		}else {
			if(StrUtils.isNotEmpty(affiliationMonth)) {
				affiliationMonth = affiliationMonth.replace("-","");
			}
			versionName = affiliationMonth+"月动态版"+vesionNum+"-"+lastDate;
		}
		return versionName;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public synchronized void finalizeCreateSupplyPlanVersion(String priceVersionId, String versionType, String userName) {
		log.info("###############定稿时创建供货计划版本   Start: "+ LocalDateTime.now());
		PriceVersion priceVersion = supplyPlanVersionMapper.selectPriceVersion(priceVersionId, IsDeleteEnum.NO.getKey());
		if(priceVersion == null) {
			log.error("##########货值定稿创建供货计划基于货值版本不存在："+ priceVersionId);
			return;
		}else {
			try {
				String projectId = priceVersion.getProjectId();
				String stageId = priceVersion.getProjectfId();
				//归属月份(已货值为准)
				String affiliationMonth  = "";
				String versionNum = "";
				String supplyPlanVersionId = "";
				String logContent = "";
				String beforeState = "";
				String afterState = "";
				String event = VersionEventEnum.SYS_GENERATE.getKey();
				if(priceVersion.getAscriptionDate() != null) {
					affiliationMonth  = LocalDateTimeUtils.formatDate(priceVersion.getAscriptionDate(),"yyyy-MM");
				}else {
					affiliationMonth  = LocalDateTimeUtils.formatTime(priceVersion.getCreateTime(),"yyyy-MM");
				}
				//货值版本详情数据
				List<PriceValueCollectDto> priceValueList = supplyPlanVersionDetailMapper.selectPriceValueOrgCollect(priceVersionId,IsDeleteEnum.NO.getKey());
				if(CollectionUtils.isEmpty(priceValueList)) {
					log.error("货值定稿创建供货计划基于货值版本详情不存在："+ priceVersionId);
					return;
				}else {
					//当前分期最新动态版供货计划
					SupplyPlanVersion newestDynamicVersion = supplyPlanVersionMapper.selectNewestDynamicVersionByProjectFId(stageId,versionType,affiliationMonth,IsDeleteEnum.NO.getKey());
					//确认版本
					SupplyPlanVersion confirmVersion = supplyPlanVersionMapper.selectConfirmSupplyVersion(stageId,affiliationMonth,SupplyConfirmStatusEnum.CONFIRMED.getKey(),IsDeleteEnum.NO.getKey());
					//当前分期最新预算版数据（判断是否延迟供货标识）
					List<SupplyPlanVersionDetail> newestBudgetDetailList = supplyPlanVersionDetailMapper.selectNewestBudgetDetailList(stageId,IsDeleteEnum.NO.getKey());
					//处理货值详情数据
					priceValueList = handlePriceValue(priceValueList);
					//处理延迟供货标识
					handleIsDelay(newestBudgetDetailList,priceValueList);
					if (newestDynamicVersion == null) {
						versionNum = VersionUtils.bigVersionInc("");
						supplyPlanVersionId = saveSupplyPlanVersion(newestDynamicVersion,VersionTypeEunm.DYNAMIC.getKey(), userName, priceVersion,affiliationMonth,versionNum);
						supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
						afterState = VersionStatusEnum.SYSGENERATION.getKey();
						logContent= "分期不存在"+affiliationMonth+"月度动态版供货计划，生成新版本，基于货值版本ID："+priceVersionId+"此次生产供货计划版本ID："+supplyPlanVersionId;
					}else {
						String newestSupplyVerisonId = newestDynamicVersion.getId();
						//判断签约是否有编排计划（有-生产新版本）
						boolean isSign = signPlanVersionService.supplyBoolean(newestSupplyVerisonId);
						if(isSign) {
							versionNum = VersionUtils.bigVersionInc(newestDynamicVersion.getVersionNum());
							supplyPlanVersionId = saveSupplyPlanVersion(newestDynamicVersion, VersionTypeEunm.DYNAMIC.getKey(), userName, priceVersion,affiliationMonth,versionNum);
							supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
							afterState = VersionStatusEnum.SYSGENERATION.getKey();
							logContent= "已编排签约计划，生成新版本，基于货值版本ID："+priceVersionId+"，上一版供货计划版本ID："+ newestSupplyVerisonId+"，此次生成供货计划版本ID："+supplyPlanVersionId;
							if(confirmVersion != null) {
								boolean isSignFlag = signPlanVersionService.supplyBoolean(confirmVersion.getId());
								if(!isSignFlag) {
									List<SupplyPlanVersionDetail> confirmOrgList = supplyPlanVersionDetailMapper.selectByVersionId(confirmVersion.getId(), IsDeleteEnum.NO.getKey());
									//判断数据层级是否相同，计划日期是否变更
									if(compareData(confirmOrgList,priceValueList) && isSameSupplyTime(confirmOrgList,priceValueList)) {
										updateVersionData(confirmVersion,priceValueList);
										updateVersion(priceVersion, confirmVersion);
									}
								}
							}
						}else {
							//判断数据层级是否相同，计划日期是否变更
							List<SupplyPlanVersionDetail> supplyPlanValueOrgList = supplyPlanVersionDetailMapper.selectByVersionId(newestSupplyVerisonId, IsDeleteEnum.NO.getKey());
							if(compareData(supplyPlanValueOrgList,priceValueList) && isSameSupplyTime(supplyPlanValueOrgList,priceValueList)) {
								//最新版本是否确认供货
								if(isConfirmSupply(newestDynamicVersion)) {
									versionNum = VersionUtils.bigVersionInc(newestDynamicVersion.getVersionNum());
									supplyPlanVersionId = saveSupplyPlanVersion(newestDynamicVersion, VersionTypeEunm.DYNAMIC.getKey(), userName, priceVersion,affiliationMonth,versionNum);
									supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);

									//变更供货确认版本基于的货值版本信息并刷新确认版数据
									updateVersionData(newestDynamicVersion,priceValueList);
									updateVersion(priceVersion, newestDynamicVersion);
									afterState = VersionStatusEnum.SYSGENERATION.getKey();
									logContent= "产品楼栋一致，计划日期没变，没有编排签约计划，已确认供货，生成新版本,同时更新供货确认的供货计划基于的货值版本并刷新数据，基于货值版本ID："+priceVersionId+"，上一版供货计划版本ID："+ newestSupplyVerisonId+"，此次生成供货计划版本ID："+supplyPlanVersionId;
								}else {
									//没有确认 变更版本信息并刷新版本详情数据
									updateVersionData(newestDynamicVersion,priceValueList);
									updateVersion(priceVersion, newestDynamicVersion);
									supplyPlanVersionId = newestDynamicVersion.getId();
									versionNum = newestDynamicVersion.getVersionNum();
									beforeState = VersionStatusEnum.SYSGENERATION.getKey();
									afterState =VersionStatusEnum.SYSGENERATION.getKey();
									event = VersionEventEnum.SYS_REFRESH.getKey();
									logContent= "产品楼栋一致，计划日期没变，没有编排签约计划，没有确认供货，刷新版本数据，基于货值版本ID："+priceVersionId+"，刷新供货计划版本ID："+newestDynamicVersion.getId();

									if(confirmVersion != null) {
										boolean isSignFlag = signPlanVersionService.supplyBoolean(confirmVersion.getId());
										if(!isSignFlag) {
											List<SupplyPlanVersionDetail> confirmOrgList = supplyPlanVersionDetailMapper.selectByVersionId(confirmVersion.getId(), IsDeleteEnum.NO.getKey());
											//判断数据层级是否相同，计划日期是否变更
											if(compareData(confirmOrgList,priceValueList) && isSameSupplyTime(confirmOrgList,priceValueList)) {
												updateVersionData(confirmVersion,priceValueList);
												updateVersion(priceVersion, confirmVersion);
											}
										}
									}

								}
							}else {
								versionNum = VersionUtils.bigVersionInc(newestDynamicVersion.getVersionNum());
								supplyPlanVersionId = saveSupplyPlanVersion(newestDynamicVersion, VersionTypeEunm.DYNAMIC.getKey(), userName, priceVersion,affiliationMonth,versionNum);
								supplyPlanVersionDetailMapper.insertBatch(priceValueList, supplyPlanVersionId);
								afterState =VersionStatusEnum.SYSGENERATION.getKey();
								logContent= "产品楼栋不一致或计划日期变动，没有编排签约计划，生成新版本，基于货值版本ID："+priceVersionId+"，上一版版供货计划版本ID："+ newestSupplyVerisonId+"，此次生成供货计划版本ID："+supplyPlanVersionId;
								//是否确认供货（有-生产新版本；无-只刷新数据）
								if(confirmVersion != null) {
									boolean isSignFlag = signPlanVersionService.supplyBoolean(confirmVersion.getId());
									if(!isSignFlag) {
										List<SupplyPlanVersionDetail> confirmOrgList = supplyPlanVersionDetailMapper.selectByVersionId(confirmVersion.getId(), IsDeleteEnum.NO.getKey());
										//判断数据层级是否相同，计划日期是否变更
										if(compareData(confirmOrgList,priceValueList) && isSameSupplyTime(confirmOrgList,priceValueList)) {
											updateVersionData(confirmVersion,priceValueList);
											updateVersion(priceVersion, confirmVersion);
										}
									}
								}

							}
						}
					}

					try {
						//刷新确认供货表
						supplyConfirmRecordDetailService.initSupplyConfirmReport(affiliationMonth,projectId);
					} catch (Exception e) {
						log.error("######刷新确认供货表 errorMsg: ", e.toString());
						saveLog("供货计划","刷新确认供货表",e.toString(),IsSuccessEnum.FAIL.getKey());
					}

					String versionName = prepareVersionName(versionType,versionNum,null,affiliationMonth,"","");

					versionLogService.saveVersionLogInfo(projectId,stageId,ModuleTypeEunm.SUPPLY_PLAN.getKey(),
							event,supplyPlanVersionId,versionName,beforeState,afterState,ModifySourceTypeEunm.TWO.getKey(),
							priceVersion.getId(),Constants.SYS,LocalDateTime.now(),"定稿创建或刷新供货计划版本",logContent,IsDeleteEnum.NO.getKey(),Constants.SYS,LocalDateTime.now());

					saveLog("供货计划","定稿创建供货计划版本",logContent,IsSuccessEnum.SUCCESS.getKey());
				}
			}catch (Exception e) {
				log.error("##### 定稿创建供货计划版本 失败", e);
				saveLog("供货计划","定稿创建供货计划版本",e.getMessage(),IsSuccessEnum.FAIL.getKey());
			}
		}
		log.info("###############定稿时创建供货计划版本   End: "+ LocalDateTime.now());
	}

	/**
	 *
	 * @Description：是否定稿
	 * @date：2020年3月2日 上午9:58:43
	 */
	private boolean isFinalizeVersion(SupplyPlanVersion newestVersion) {
		Integer isFinalize =  newestVersion.getIsFinalize();
		if(isFinalize != null) {
			if(isFinalize.intValue() == IsDeleteEnum.YES.getKey()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @Description：是否确认供货
	 * @date：2020年3月2日 上午9:58:43
	 */
	private boolean isConfirmSupply(SupplyPlanVersion newestVersion) {
		Integer confirmStatus =  newestVersion.getConfirmStatus();
		if(confirmStatus != null) {
			if(confirmStatus.intValue() == SupplyConfirmStatusEnum.CONFIRMED.getKey()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @Description：刷新版本数据
	 * @date：2020年3月2日 上午9:58:43
	 */
	private void updateVersionData(SupplyPlanVersion newestVersion, List<PriceValueCollectDto> priceValueList) {
		supplyPlanVersionDetailMapper.deleteRecord(newestVersion.getId());
		supplyPlanVersionDetailMapper.insertBatch(priceValueList, newestVersion.getId());
	}

	/**
	 *
	 * 方法描述：生成月度动态版供货计划时，需与当年年初预算版供货计划进行对比，标明“延迟供货”
	 * 创建人：yyd
	 * 创建时间：2019年11月12日 下午9:51:42
	 */
	private void handleIsDelay(List<SupplyPlanVersionDetail> newestBudgetDetailList,List<PriceValueCollectDto> priceValueList) {
		//判断是否延迟供货（供货实际时间 大于 计划供货时间）
		for(PriceValueCollectDto dto : priceValueList) {
			String fullPathNamePrice = dto.getOrgFullPath();
			LocalDateTime supplyTimePrice = dto.getSupplyTime();
			LocalDateTime supplyActualTimePrice = dto.getActualSupplyDate() == null ? dto.getSupplyTimeVirtual() : dto.getActualSupplyDate();
			if(supplyTimePrice != null) {
				if(supplyActualTimePrice != null) {
					//已供
					if(supplyActualTimePrice.isAfter(supplyTimePrice)) {
						if(supplyActualTimePrice.getMonthValue() != supplyTimePrice.getMonthValue()) {
							dto.setIsDelay(IsDelayEnum.YES.getKey());
						}
					}
				}else {
					//未供
					if(CollectionUtils.isNotEmpty(newestBudgetDetailList)) {
						for(SupplyPlanVersionDetail detail : newestBudgetDetailList) {
							String fullPathNameSupply = detail.getOrgFullPath();
							if(StrUtils.isNotEmpty(fullPathNameSupply) && StrUtils.isNotEmpty(fullPathNamePrice)) {
								if(fullPathNameSupply.equals(fullPathNamePrice)) {
									LocalDateTime supplyDate = detail.getSupplyDate();
									if(supplyDate != null && supplyTimePrice.isAfter(supplyDate)) {
										if(supplyTimePrice.getMonthValue() != supplyDate.getMonthValue()) {
											dto.setIsDelay(IsDelayEnum.YES.getKey());
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	/**
	 *
	 * 方法描述：变更版本信息
	 * 创建人：yyd
	 * 创建时间：2019年11月6日 下午3:49:55
	 */
	private void updateVersion(PriceVersion priceVersion, SupplyPlanVersion newestVersion) {
		newestVersion.setSourcePriceId(priceVersion.getId());
		newestVersion.setSourcePriceName(priceVersion.getVersionName());
		newestVersion.setSourcePriceNum(priceVersion.getVersionNum());
		newestVersion.setSourceBuildplanVersionId(priceVersion.getSourcePlan());
		newestVersion.setSourceBuildplanVersionName(priceVersion.getSourcePlanDetail());
		newestVersion.setUpdateBy(Constants.SYS);
		newestVersion.setUpdateTime(LocalDateTime.now());
		newestVersion.setIsFinalize(priceVersion.getIsFinalization());
		supplyPlanVersionMapper.updateById(newestVersion);
	}
	/**
	 *
	 * @Description：处理货值版本数据
	 * @date：2020年3月2日 上午9:58:43
	 */
	private List<PriceValueCollectDto> handlePriceValue(List<PriceValueCollectDto> priceValueList) {
		//设置层级的属性标签
		for (PriceValueCollectDto dto : priceValueList) {
			String type = dto.getType();
			if(type.equals(OrgTypeEunm.ORG_HOUSE_PACKAGE.getKey())
					|| type.equals(OrgTypeEunm.ORG_SALE_PACKAGE.getKey())
					|| type.equals(OrgTypeEunm.ORG_NOT_SALE_PACKAGE.getKey())
					|| type.equals(OrgTypeEunm.ORG_SALING_PARKING.getKey())
					|| type.equals(OrgTypeEunm.ORG_NOT_SALING_PARKING.getKey())) {
				String pid = dto.getPid();
				PriceValueCollectDto parentObj = getParentData(priceValueList,pid);
				if(parentObj != null) {
					dto.setIsSupply(parentObj.getIsSupply());
					dto.setIsParking(parentObj.getIsParking());
					dto.setBusinessType(parentObj.getBusinessType());
					dto.setBusinessTypeName(parentObj.getBusinessTypeName());
					dto.setFreeType(parentObj.getFreeType());
					dto.setFreeTypeName(parentObj.getFreeTypeName());
					dto.setProType(parentObj.getProType());
					dto.setProTypeName(parentObj.getProTypeName());
				}
			}
		}

		//供货实际赋值：（已供：供货实际=供货计划;未供：供货实际为空不存在
		for (PriceValueCollectDto dto : priceValueList) {
			Integer isSupply = dto.getIsSupply();
			if(isSupply != null && isSupply.intValue() == 1) {
				dto.setRoomNumActual(dto.getRoomNum());
				dto.setParkingNumActual(dto.getParkingNum());
				dto.setForsaleParkingNumActual(dto.getForsaleParkingNum());
				dto.setAreaActual(dto.getSaleArea());
				dto.setAveragePriceHouseActual(dto.getAveragePriceHouse());
				dto.setAveragePriceParkingActual(dto.getAveragePriceParking());
				dto.setAveragePriceParkingForsaleActual(dto.getAveragePriceParkingForsale());
				dto.setHouseCommodityValueActual(dto.getHouseCommodityValue());
				dto.setNotCommodityValueActual(dto.getNotCommodityValue());
				dto.setCommodityValueActual(dto.getCommodityValue());
				dto.setActualSupplyDate(dto.getActualSupplyDate());
				dto.setSupplyTimeVirtual(dto.getSupplyTimeVirtual());
			}
		}
		//生成全路径
		setPriceOrgFullpath(priceValueList,Constants.ROOT_NODE_PID);

		return priceValueList;
	}
	/**
	 *
	 * 方法描述：获取父级数据
	 * 创建人：yyd
	 * 创建时间：2019年11月8日 上午9:14:31
	 */
	private PriceValueCollectDto getParentData(List<PriceValueCollectDto> priceValueList, String pid) {
		for(PriceValueCollectDto dto : priceValueList) {
			if(dto.getId().equals(pid)) {
				return dto;
			}
		}
		return null;
	}
	/**
	 *
	 * 方法描述：保存供货计划版本信息
	 * 创建人：yyd
	 * 创建时间：2019年11月1日 上午10:41:27
	 */
	private String saveSupplyPlanVersion(SupplyPlanVersion supplyPlanVersionNewest,
										 String versionType,String alias,PriceVersion priceVersion,String affiliationMonth,String versionNum) {

		SupplyPlanVersion versionDB = new SupplyPlanVersion();
		versionDB.setId(UUIDUtils.create());
		versionDB.setVersionName(VersionTypeEunm.getValueByKey(versionType));
		versionDB.setVersionType(versionType);
		versionDB.setVersionNum(versionNum);
		versionDB.setAffiliationMonth(affiliationMonth);
		versionDB.setLastVersion(supplyPlanVersionNewest == null ? null : supplyPlanVersionNewest.getId());
		versionDB.setProjectId(priceVersion.getProjectId());
		versionDB.setProjectfId(priceVersion.getProjectfId());
		versionDB.setStageCode(priceVersion.getStageCode());
		versionDB.setStageName(priceVersion.getStageName());
		versionDB.setVersionState(VersionStatusEnum.SYSGENERATION.getKey());
		versionDB.setSourcePriceId(priceVersion.getId());
		versionDB.setSourcePriceName(priceVersion.getVersionName());
		versionDB.setSourcePriceNum(priceVersion.getVersionNum());
		versionDB.setSourceBuildplanVersionId(priceVersion.getSourcePlan());
		versionDB.setSourceBuildplanVersionName(priceVersion.getSourcePlanDetail());
		versionDB.setIsAssessmentVersion(supplyPlanVersionNewest == null ? priceVersion.getIsAssessmentVersion() : null);
		versionDB.setIsFinalize(priceVersion.getIsFinalization());
		versionDB.setCreateBy(alias);
		versionDB.setCreateTime(LocalDateTime.now());
		versionDB.setUpdateBy(alias);
		versionDB.setUpdateTime(LocalDateTime.now());
		versionDB.setIsDelete(IsDeleteEnum.NO.getKey());
		int count = supplyPlanVersionMapper.insert(versionDB);
		return versionDB.getId();
	}
	/**
	 * 方法描述：比较两个版本数据的供货计划日期是否一致
	 * @return boolean
	 * 创建人：yyd
	 * 创建时间：2019年11月1日 上午10:42:10
	 */
	public boolean isSameSupplyTime(List<SupplyPlanVersionDetail> supplyPlanValueOrgList,List<PriceValueCollectDto> priceValueList) {
		supplyPlanValueOrgList = setSupplyOrgFullpath(supplyPlanValueOrgList,Constants.ROOT_NODE_PID);
		priceValueList = setPriceOrgFullpath(priceValueList,Constants.ROOT_NODE_PID);
		//计划日期是否相同
		for(SupplyPlanVersionDetail supply : supplyPlanValueOrgList) {
			LocalDateTime supplyDate = supply.getSupplyDate();
			String supplyOrgFullPath = supply.getOrgFullPathName();
			for(PriceValueCollectDto price : priceValueList) {
				LocalDateTime supplyTime = price.getSupplyTime();
				String priceOrgFullPath = price.getOrgFullPathName();
				if(supplyOrgFullPath.equals(priceOrgFullPath)) {
					if(!compareSupplyDate(supplyDate,supplyTime)) {
						return false;
					}
				}
			}
		}
		return true;
	}
	/**
	 *
	 * @Description：比较版本供货日期
	 * @date：2020年3月2日 上午9:58:43
	 */
	public boolean compareSupplyDate(LocalDateTime supplyDate, LocalDateTime supplyDate2) {
		if (null == supplyDate && null == supplyDate2) {
			return true;
		}

		if (null == supplyDate && supplyDate2 != null) {
			return false;
		}

		if (supplyDate != null && null == supplyDate2) {
			return false;
		}

		if (supplyDate != null && supplyDate2 != null) {
			String supplyDateStr = LocalDateTimeUtils.formatTime(supplyDate, YEAR_MONTH_DAY);
			String supplyDate2Str =  LocalDateTimeUtils.formatTime(supplyDate2, YEAR_MONTH_DAY);
			return supplyDateStr.equals(supplyDate2Str);
		}
		return true;
	}
	/**
	 * 方法描述：比较两个版本数据的层级是否一致
	 * @return boolean
	 * 创建人：yyd
	 * 创建时间：2019年11月1日 上午10:42:10
	 */
	public boolean compareData(List<SupplyPlanVersionDetail> supplyPlanValueOrgList,List<PriceValueCollectDto> priceValueList) {
		supplyPlanValueOrgList = setSupplyOrgFullpath(supplyPlanValueOrgList,Constants.ROOT_NODE_PID);
		priceValueList = setPriceOrgFullpath(priceValueList,Constants.ROOT_NODE_PID);
		if(!isSameOrgTree(supplyPlanValueOrgList,priceValueList)) {
			return false;
		}
		return true;
	}
	/**
	 *
	 * @Description：层级比较
	 * @date：2020年3月2日 上午9:58:43
	 */
	private boolean isSameOrgTree(List<SupplyPlanVersionDetail> supplyPlanValueOrgList,List<PriceValueCollectDto> priceValueList) {
		List<String> supplyOrgTree = new ArrayList<>();
		List<String> priceOrgTree = new ArrayList<>();
		for(SupplyPlanVersionDetail org : supplyPlanValueOrgList ) {
			String type = org.getType();
			if(type.equals(OrgTypeEunm.ORG_BUILD.getKey()) ) {
				supplyOrgTree.add(org.getOrgFullPath());
			}
		}

		for(PriceValueCollectDto dto : priceValueList ) {
			String type = dto.getType();
			if(type.equals(OrgTypeEunm.ORG_BUILD.getKey())) {
				priceOrgTree.add(dto.getOrgFullPath());
			}
		}

		Map<String,Integer> map = new HashMap<String,Integer>();
		List<String> diff = new ArrayList<String>();
		for (String key : supplyOrgTree) {
			map.put(key, 1);
		}
		for (String key : priceOrgTree) {
			Integer cc = map.get(key);
			if(cc!=null){
				map.put(key, ++cc);
				continue;
			}
			map.put(key, 1);
		}
		for(Map.Entry<String, Integer> entry:map.entrySet()) {
			if(entry.getValue()==1)  {
				diff.add(entry.getKey());
			}
		}
		if(diff.size() > 0) {
			return false;
		}
		return true;
	}
	/**
	 *
	 * 方法描述：设置货值详情全路劲
	 * 创建人：yyd
	 * 创建时间：2019年11月11日 下午7:52:24
	 */
	private List<PriceValueCollectDto> setPriceOrgFullpath(List<PriceValueCollectDto> priceValueList, String pid) {
		String fullPath ="";
		String fullPathName ="";
		for(PriceValueCollectDto dto : priceValueList) {
			if(dto.getId().equals(pid)) {
				fullPath= dto.getOrgFullPath();
				fullPathName= dto.getOrgFullPathName();
			}
		}
		for(PriceValueCollectDto dto : priceValueList) {
			if(dto.getPid().equals(pid)) {
				if(dto.getType().equals(OrgTypeEunm.ORG_PRODUCT.getKey())) {
					dto.setOrgFullPath(fullPath+"/"+dto.getProProductCode()+"/"+dto.getCode());
					dto.setOrgFullPathName(fullPathName+"/"+dto.getProProductType()+"/"+dto.getName());
				}else {
					dto.setOrgFullPath(fullPath+"/"+dto.getCode());
					dto.setOrgFullPathName(fullPathName+"/"+dto.getName());
				}
				setPriceOrgFullpath(priceValueList,dto.getId());
			}
		}
		return priceValueList;
	}
	/**
	 *
	 * 方法描述：设置供货计划详情全路劲
	 * 创建人：yyd
	 * 创建时间：2019年11月11日 下午7:52:24
	 */
	private List<SupplyPlanVersionDetail> setSupplyOrgFullpath(List<SupplyPlanVersionDetail> supplyPlanValueOrgList, String pid) {
		String fullPath ="";
		String fullPathName = "";
		for(SupplyPlanVersionDetail org : supplyPlanValueOrgList) {
			if(org.getId().equals(pid)) {
				fullPath= org.getOrgFullPath();
				fullPathName = org.getOrgFullPathName();
			}
		}
		for(SupplyPlanVersionDetail org : supplyPlanValueOrgList) {
			if(org.getPid().equals(pid)) {
				if(org.getType().equals(OrgTypeEunm.ORG_PRODUCT.getKey())) {
					org.setOrgFullPath(fullPath+"/"+org.getProProductCode()+"/"+org.getOrgCode());
					org.setOrgFullPathName(fullPathName+"/"+org.getProProductType()+"/"+org.getOrgName());
				}else {
					org.setOrgFullPath(fullPath+"/"+org.getOrgCode());
					org.setOrgFullPathName(fullPathName+"/"+org.getOrgName());
				}
				setSupplyOrgFullpath(supplyPlanValueOrgList,org.getId());
			}
		}
		return supplyPlanValueOrgList;
	}

	@Override
	public boolean isExistBudgetVersion(String projectFId) {
		String versionIdentify = "";
		String versionAttr = "";
		String budgetYear = "";
		if(!stageService.isActiveStage(projectFId)) {
			throw new MsgException(CodeEnum.CREATE_STAGE_INACTIVE_ERROR);
		}
		//获取分期下最新供货计划版本
		SupplyPlanVersion version = supplyPlanVersionMapper.selectNewestVersionByProjectFid(projectFId,IsDeleteEnum.NO.getKey());
		if(version == null) {
			throw new MsgException(CodeEnum.NOT_EXISTENT_VERSION);
		}
		
		String month = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "MM");
		SysDictionary dictionary = sysDictionaryService.selectDictionaryByTypeCode(Constants.BUDGET_CYCLE_TYPE_CODE,month);
		if(dictionary == null) {
			throw new MsgException(CodeEnum.CANNOT_CREATE_VERSION);
		}else {
			String budgetCycleCode = dictionary.getDictCode();
			if(BudgetCycleEnum.ALL_YEAR_BUDGET.getKey().equals(budgetCycleCode)) {
				versionIdentify = VersionIdentifyEnum.ALL_YEAR.getKey();
				budgetYear = LocalDateTime.now().getYear()+"";
			}
			if(BudgetCycleEnum.MID_YEAR_BUDGET.getKey().equals(budgetCycleCode)) {
				versionIdentify = VersionIdentifyEnum.MID_YEAR.getKey();
				budgetYear = LocalDateTime.now().getYear()+"";
			}
			if(BudgetCycleEnum.NEXT_ALL_YEAR_BUDGET.getKey().equals(budgetCycleCode)) {
				versionIdentify = VersionIdentifyEnum.ALL_YEAR.getKey();
				budgetYear = LocalDateTime.now().getYear() +1+"";
			}
			
			if (version.getVersionType().equals(VersionTypeEunm.INVESTMENT.getKey())) {
				// 战规前预算版本-即投资版（基于价格管理最新投资版）
				versionAttr = VersionAttrEnum.BEFORE_WARPLAN.getKey();
			} else {
				// 战规后预算版本-基于价格管理最新版本（战规版、大定价版、动态版）
				versionAttr = VersionAttrEnum.AFTER_WARPLAN.getKey();
			}

			List<SupplyPlanVersion> list = supplyPlanVersionMapper.selectBudgetVersionByFId(projectFId,budgetYear,versionAttr,versionIdentify,VersionTypeEunm.BUDGET.getKey(),IsDeleteEnum.NO.getKey());
			if(CollectionUtils.isNotEmpty(list)) {
				return true;
			}
		}
		return false;
	}
	
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public synchronized void createSupplyBudgetVersion(String projectFId,String userName) {
		log.info("###############创建供货计划预算版本   Start: "+ LocalDateTime.now());
		//获取分期下最新供货计划版本
		SupplyPlanVersion version = supplyPlanVersionMapper.selectNewestVersionByProjectFid(projectFId,IsDeleteEnum.NO.getKey());
		if(version == null) {
			throw new MsgException(CodeEnum.SUPPLY_PLAN_VERSION_ERROR);
		}
		String month = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "MM");
		/**
		 * 1-3 月 当年全年
		 * 5-8月 当年年中
		 * 10-12 下一年全年
		 */
		SysDictionary dictionary = sysDictionaryService.selectDictionaryByTypeCode(Constants.BUDGET_CYCLE_TYPE_CODE,month);
		String versionIdentify = "";
		String versionAttr = "";
		String budgetYear = "";
		if(dictionary == null) {
			throw new MsgException(CodeEnum.CANNOT_CREATE_VERSION);
		}else {
			String budgetCycleCode = dictionary.getDictCode();
			if(BudgetCycleEnum.ALL_YEAR_BUDGET.getKey().equals(budgetCycleCode)) {
				versionIdentify = VersionIdentifyEnum.ALL_YEAR.getKey();
				budgetYear = LocalDateTime.now().getYear()+"";
			}
			if(BudgetCycleEnum.MID_YEAR_BUDGET.getKey().equals(budgetCycleCode)) {
				versionIdentify = VersionIdentifyEnum.MID_YEAR.getKey();
				budgetYear = LocalDateTime.now().getYear()+"";
			}
			if(BudgetCycleEnum.NEXT_ALL_YEAR_BUDGET.getKey().equals(budgetCycleCode)) {
				versionIdentify = VersionIdentifyEnum.ALL_YEAR.getKey();
				budgetYear = LocalDateTime.now().getYear() +1+"";
			}
			PriceVersion priceVersion = supplyPlanVersionMapper.selectPriceVersion(version.getSourcePriceId(), IsDeleteEnum.NO.getKey());
			if(priceVersion == null) {
				throw new MsgException(CodeEnum.SUPPLY_PRICE_NOT_EXIST);
			}
			if (priceVersion.getVersionType().equals(VersionTypeEunm.INVESTMENT.getKey())) {
				// 战规前预算版本-即投资版（基于价格管理最新投资版）
				versionAttr = VersionAttrEnum.BEFORE_WARPLAN.getKey();
			} else {
				// 战规后预算版本-基于价格管理最新版本（战规版、大定价版、动态版）
				versionAttr = VersionAttrEnum.AFTER_WARPLAN.getKey();
			}
			try {
				List<SupplyPlanVersionDetail> list = supplyPlanVersionDetailMapper.selectByVersionId(version.getId(), IsDeleteEnum.NO.getKey());
				SupplyPlanVersion newestVersion = supplyPlanVersionMapper.selectNewestVersion(projectFId,VersionTypeEunm.BUDGET.getKey(),IsDeleteEnum.NO.getKey());
				String versionNum = VersionUtils.bigVersionInc(newestVersion == null ? "" : newestVersion.getVersionNum());
				String supplyPlanVersionId = saveBudgetSupplyPlanVersion(newestVersion,userName,version,versionIdentify,versionAttr,budgetYear);
				supplyPlanVersionDetailMapper.insertBudgetBatch(list, supplyPlanVersionId);

				saveLog("供货计划","创建版本","创建预算版本",IsSuccessEnum.SUCCESS.getKey());

				String versionName = prepareVersionName(VersionTypeEunm.BUDGET.getKey(),versionNum,null,"",budgetYear,versionIdentify);
				versionLogService.saveVersionLogInfo(version.getProjectId(),version.getProjectfId(),ModuleTypeEunm.SUPPLY_PLAN.getKey(),
						VersionEventEnum.MANUALCREATE.getKey(),supplyPlanVersionId,versionName,
						"",VersionStatusEnum.SYSGENERATION.getKey(),ModifySourceTypeEunm.TWO.getKey(),
						version.getSourcePriceId(),userName,LocalDateTime.now(),"创建或刷新供货计划版本","创建预算版供货计划",IsDeleteEnum.NO.getKey(),userName,LocalDateTime.now());

			} catch (Exception e) {
				log.error("##### 创建预算版本 失败", e);
				saveLog("供货计划","创建版本",e.getMessage(),IsSuccessEnum.FAIL.getKey());
			}

		}
		log.info("###############创建供货计划预算版本   End: "+ LocalDateTime.now());
	}

	private String saveBudgetSupplyPlanVersion(SupplyPlanVersion supplyPlanVersionNewest,
											   String alias,SupplyPlanVersion version,String versionIdentify,String versionAttr,String budgetYear) {

		SupplyPlanVersion SupplyPlanVersionDB = new SupplyPlanVersion();
		SupplyPlanVersionDB.setId(UUIDUtils.create());
		SupplyPlanVersionDB.setLastVersion(supplyPlanVersionNewest == null ? null : supplyPlanVersionNewest.getId());
		SupplyPlanVersionDB.setVersionName(VersionTypeEunm.getValueByKey(VersionTypeEunm.BUDGET.getKey()));
		SupplyPlanVersionDB.setVersionType(VersionTypeEunm.BUDGET.getKey());
		SupplyPlanVersionDB.setVersionNum(VersionUtils.bigVersionInc(supplyPlanVersionNewest == null ? "" : supplyPlanVersionNewest.getVersionNum()));
		SupplyPlanVersionDB.setProjectId(version.getProjectId());
		SupplyPlanVersionDB.setProjectfId(version.getProjectfId());
		SupplyPlanVersionDB.setStageCode(version.getStageCode());
		SupplyPlanVersionDB.setStageName(version.getStageName());
		SupplyPlanVersionDB.setVersionState(VersionStatusEnum.SYSGENERATION.getKey());
		SupplyPlanVersionDB.setSourcePriceId(version.getSourcePriceId());
		SupplyPlanVersionDB.setSourcePriceName(version.getSourcePriceName());
		SupplyPlanVersionDB.setSourcePriceNum(version.getSourcePriceNum());
		SupplyPlanVersionDB.setSourceBuildplanVersionId(version.getSourceBuildplanVersionId());
		SupplyPlanVersionDB.setSourceBuildplanVersionName(version.getSourceBuildplanVersionName());
		SupplyPlanVersionDB.setIsAssessmentVersion(version.getIsAssessmentVersion());
		SupplyPlanVersionDB.setVersionIdentify(versionIdentify);
		SupplyPlanVersionDB.setSourceSupplyId(version.getId());
		SupplyPlanVersionDB.setBudgetYear(budgetYear);
		SupplyPlanVersionDB.setVersionAttr(versionAttr);
		SupplyPlanVersionDB.setCreateBy(alias);
		SupplyPlanVersionDB.setCreateTime(LocalDateTime.now());
		SupplyPlanVersionDB.setUpdateBy(alias);
		SupplyPlanVersionDB.setUpdateTime(LocalDateTime.now());
		SupplyPlanVersionDB.setIsDelete(IsDeleteEnum.NO.getKey());
		int count = supplyPlanVersionMapper.insert(SupplyPlanVersionDB);
		String supplyPlanVersionId = SupplyPlanVersionDB.getId();
		return supplyPlanVersionId;
	}

	@Override
	public void setAssessmentTag(String versionId, String projectFid) {
		List<SupplyPlanVersion> list = supplyPlanVersionMapper.selectAssessmentVersion(versionId,projectFid,IsDeleteEnum.NO.getKey(),isAssessmentVersionEnum.YES.getKey());
		if(CollectionUtils.isEmpty(list)) {
			throw new MsgException(CodeEnum.NOT_SET_ASSESSMENT_VERSION);
		}else {
			//1、删除原有的考核标签
			supplyPlanVersionMapper.deleteExistedAssessmentTag(projectFid,isAssessmentVersionEnum.YES.getKey(),IsDeleteEnum.NO.getKey());
			//设置供货投资版考核标签
			supplyPlanVersionMapper.setInvestmentAssessmentTag(versionId,projectFid,isAssessmentVersionEnum.YES.getKey(),IsDeleteEnum.NO.getKey());
		}
	}

	@Override
	public void updateAssessmentTag(String versionId,String projectFid) {
		SupplyPlanVersion version = supplyPlanVersionMapper.selectVersionByProjectFid(projectFid,versionId,IsDeleteEnum.NO.getKey());
		if(version != null) {
			//1、删除原有的考核标签
			supplyPlanVersionMapper.deleteExistedAssessmentTag(projectFid,isAssessmentVersionEnum.YES.getKey(),IsDeleteEnum.NO.getKey());
			//2、重新设置新的考核标签
			supplyPlanVersionMapper.setAssessmentTag(version.getId(),isAssessmentVersionEnum.YES.getKey(),IsDeleteEnum.NO.getKey());
			//3,修改签约考核标签
			signPlanVersionService.updateAssessmentVersion(version.getId(),projectFid);
		}else {
			signPlanVersionService.updateAssessmentVersion(null,projectFid);
		}
	}

	@Override
	public void isNeedSpplyConfirm(String projectId) {
		/**
		 * 规则：项目有动态版供货计划时，即需要进行供货确认，
		 */
		//版本归属月份
		String affiliationMonth =  getAffiliationMonth("");
		//1、项目有动态版供货计划时
		List<SupplyPlanVersion> list = supplyPlanVersionMapper.selectNewestDynamicVersion(projectId,affiliationMonth,IsDeleteEnum.NO.getKey());
		if(CollectionUtils.isEmpty(list)) {
			throw new MsgException(CodeEnum.NOT_NEED_SUPPLY_CONFIRM);
		}
		
		List<MdmStage> stageList = stageService.selectByProjectId(projectId, IsDeleteEnum.NO.getKey());
		List<String> stageStatus = stageList.stream().map(s-> s.getStatus()).collect(Collectors.toList());
		if(!stageStatus.contains(StageStatusEnum.CTIVE.getKey())) {
			throw new MsgException(CodeEnum.SUPPLY_NOT_CANCEL_CONFIRM);
		}
		
	}

	@Override
	public List<SupplyPlanVersion> selectNewestDynamicVersion(String projectId, String versionDate) {
		List<SupplyPlanVersion> dataList = Collections.synchronizedList(new ArrayList<>());
		List<Map<String, Object>> stageList = supplyPlanVersionMapper.selectStageByProjectId(projectId,IsDeleteEnum.NO.getKey());
		if(CollectionUtils.isNotEmpty(stageList)) {
			for(Map<String, Object> map: stageList) {
				String stageId = String.valueOf(map.get("projectf_id"));
				boolean isActiveStage = stageService.isActiveStage(stageId);
				if(!isActiveStage) {
					continue;
				}
				//如果没有确认，取最新版本
				List<SupplyPlanVersion> list = supplyPlanVersionMapper.selectNewestDynamicVersionByStageId(stageId,versionDate,SupplyConfirmStatusEnum.CONFIRMED.getKey(),IsDeleteEnum.NO.getKey());
				if(CollectionUtils.isEmpty(list)) {
					list = supplyPlanVersionMapper.selectNewestDynamicVersionByStageId(stageId,versionDate,SupplyConfirmStatusEnum.UNCONFIRMED.getKey(), IsDeleteEnum.NO.getKey());
				}
				dataList.addAll(list);
			}
		}
		return dataList;
	}

	@Override
	public SupplyPlanVersionDto selectVersionData(String versionId) {
		return supplyPlanVersionMapper.selectVersionData(versionId,IsDeleteEnum.NO.getKey());
	}

	@Override
	public List<SupplyPlanVersion> queryNeedSupplyConfirmVersion(String curTimeStr) {
		return supplyPlanVersionMapper.selectNeedSupplyConfirmVersion(curTimeStr,IsDeleteEnum.NO.getKey());
	}

	@Override
	public synchronized List<SupplyPlanVersionDto> selectDynamicVersionByOrgIdAndDate(List<String> projectIds, String projectName, Integer status,String versionDate,String endConfirmDate) {
		return supplyPlanVersionMapper.selectDynamicVersionByOrgIdAndDate(projectIds,projectName,status,versionDate,endConfirmDate,IsDeleteEnum.NO.getKey());
	}

	@Override
	public List<SupplyPlanVersion> queryFinalizeVersions(List<String> priceIds, String versionType) {
		List<SupplyPlanVersion> list = Collections.synchronizedList(new ArrayList<>());
		for(String priceVersionId : priceIds) {
			SupplyPlanVersion version = supplyPlanVersionMapper.selectFinalizeVersion(priceVersionId,versionType,IsDeleteEnum.NO.getKey());
			if(version != null) {
				list.add(version);
			}
		}
		return list;
	}

	@Override
	public void setFinalizeVersion(List<String> versionIds) {
		supplyPlanVersionMapper.setFinalizeVersion(versionIds,IsDeleteEnum.YES.getKey());
	}

	@Override
	public List<SupplyPlanVersion> queryUnconfirmedVersions(String date, String versionType) {
		return supplyPlanVersionMapper.selectUnconfirmedVersions(date,versionType,IsDeleteEnum.NO.getKey());
	}

	@Override
	public void deleteTodo(List<String> projectList) {
		if(CollectionUtils.isNotEmpty(projectList)) {
			List<Map<String, Object>> list = supplyPlanVersionMapper.selectTodoIds(projectList,TodoTypeCodeEnum.SUPPLY_CONFIRM.getKey(),TodoStatusEnum.DEFAULT.getKey());
			if(CollectionUtils.isNotEmpty(list)) {
				IdmUser user = new IdmUser();
				user.setAlias(Constants.SYS);
				user.setUsercn(Constants.SYS_NAME);
				for(Map<String, Object> map : list) {
					String instanceId = String.valueOf(map.get("instance_id"));
					commonService.updatePortalProcess(instanceId,OperatorTypeEnum.DELETE.getKey(),user,null);
				}
			}
		}
	}

	@Override
	public void sendBackLog(String projectId, String versionId,int type) {
		ProjectOrgDto org = projectMapper.selectProjectParentData(projectId);
		String groupId = "";
		String businessId="";
		String cityId="";
		String pcUrl = "";
		String projectName="";
		if(org != null) {
			groupId = org.getGroupId();
			businessId=org.getRegionId();
			cityId=org.getCityId();
			projectName = org.getProjectName();
		}
		pcUrl = confirmTodoUrl+businessId+"/"+cityId+"/"+projectId;
		//项目PM
		List<IdmUser> userList = getProjectPm(projectId);
		PortalTodoBo doorTodoBo=new PortalTodoBo();
		//移动端地址，钉钉上收到待办时，点击后进入的地址。（可为钉钉应用首页）必传
		doorTodoBo.setMobileTaskUrl(mobileTaskUrl);
		//PC端地址，门户portal.cifi.com.cn中点击一条待办后进入的地址。必传
		doorTodoBo.setPcTaskUrl(pcUrl);
		//任务类型code
		doorTodoBo.setTodoTypeCode(TodoTypeCodeEnum.SUPPLY_CONFIRM.getKey());
		// 任务关联id
		doorTodoBo.setVersionId(versionId);
		//任务关联id类型
		doorTodoBo.setVersionIdType(VersionIdTypeEnum.SUPPLY.getKey());
		//待办组织类型
		doorTodoBo.setOrgType(TodoOrgTypeEnum.FOUR.getKey());
		//集团id
		doorTodoBo.setGroupId(groupId);
		//区域或事业部id
		doorTodoBo.setRegionId(businessId);
		//城市公司id
		doorTodoBo.setCityId(cityId);
		//项目id
		doorTodoBo.setProjectId(projectId);
		//待办内容,待办说明
		if(type == 1) {
			//待办的主题 自己定义
			doorTodoBo.setTodoType("确认供货");
			doorTodoBo.setTitle(projectName+"，已到供货确认期，请在1号6点前确认"+projectName+"项目最新供货计划，以便营销编排签约计划；超时未确认集团将进行通报晾晒");
			doorTodoBo.setContent("【进行供货确认】已到供货确认期，请在1号6点前确认"+projectName+"项目最新供货计划，以便营销编排签约计划；超时未确认集团将进行通报晾晒");
		}else {
			//待办的主题 自己定义
			doorTodoBo.setTodoType("再次确认供货");
			doorTodoBo.setTitle(projectName+"，已取消供货确认，请在1号6点前再次确认"+projectName+"项目最新供货计划，以便营销编排签约计划；超时未确认集团将进行通报晾晒");
			doorTodoBo.setContent("【再次确认供货】"+projectName+"已取消供货确认，请在1号6点前再次确认"+projectName+"项目最新供货计划，以便营销编排签约计划；超时未确认集团将进行通报晾晒");
		}
		commonService.start("", doorTodoBo,userList);
	}

	private List<IdmUser> getProjectPm(String projectId) {
		List<IdmUser> userList = Collections.synchronizedList(new ArrayList<>());
		//获取项目运营PM
		HashSet<GroupUserVo> set = idmUserService.getGroupUserInfo(Constants.PROJECT_OPERATION_PM,projectId);
		if(CollectionUtils.isNotEmpty(set)) {
			for(GroupUserVo vo : set) {
				IdmUser user = idmUserService.getByAlias(vo.getAlias());
				userList.add(user);
			}
		}
		return userList;
	}

	@Override
	public boolean saveLog(String module,String title,String content,String isSuccess) {
		SysLogBO bo = new SysLogBO();
		bo.setEvent(LogEventEnum.BROWSE);
		bo.setSource(LogSrcEnum.PC);
		bo.setModule(module);
		bo.setTitle(title);
		bo.setContent(content);
		bo.setType(LogTypeEnum.ZERO.getKey());
		bo.setIsSuccess(isSuccess);
		return sysLogService.add(bo,Constants.SYS);
	}

	@Override
	public void sendToDoMsg(String projectId, String versionId,int type) {
		List<MdmStage> stageList = stageService.selectByProjectId(projectId, IsDeleteEnum.NO.getKey());
		List<String> stageStatus = stageList.stream().map(s-> s.getStatus()).collect(Collectors.toList());
		if(stageStatus.contains(StageStatusEnum.CTIVE.getKey())) {
			sendBackLog(projectId,versionId,type);
		}else {
			throw new MsgException(CodeEnum.SUPPLY_NOT_CANCEL_CONFIRM);
		}
		
	}

	@Override
	public boolean isBetweenComfirmTime() {
		String startSuffix = Constants.CONFIRM_START_TIME;
		SysDictionary sysDictionary = sysDictionaryService.selectDictionaryByCode(SupplyConfirmCodeEnum.START.getKey());
		if(sysDictionary != null) {
			startSuffix = sysDictionary.getDictValue();
		}
		String confirmTime = getComfirmTime();
		return LocalDateTimeUtils.isConfirmTime(confirmTime,startSuffix);
	}

	@Override
	public String getComfirmTime() {
		String endSuffix = Constants.CONFIRM_END_TIME;
		SysDictionary sysDictionary = sysDictionaryService.selectDictionaryByCode(SupplyConfirmCodeEnum.END.getKey());
		if(sysDictionary != null) {
			endSuffix = sysDictionary.getDictValue();
		}
		String confirmTime = LocalDateTimeUtils.getConfirmTime(endSuffix);
		return confirmTime;
	}

	@Override
	public String getAffiliationMonth(String date) {
		String affiliationMonth = date;
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		if(isBetweenComfirmTime()) {
			String comfirmTime = getComfirmTime();
			LocalDateTime confirmTime = LocalDateTime.parse(comfirmTime, df);
			affiliationMonth = LocalDateTimeUtils.formatTime(confirmTime.minusMonths(1),DateUtils.DATE_JFP_STR);
		}else {
			affiliationMonth = LocalDateTimeUtils.formatTime(LocalDateTime.now().minusMonths(1),DateUtils.DATE_JFP_STR);
		}
		return affiliationMonth;
	}

	@Override
	public boolean supplyIsComfirm(String priceVersionId) {
		List<SupplyPlanVersion> list = supplyPlanVersionMapper.selectComfirmVersion(priceVersionId,SupplyConfirmStatusEnum.CONFIRMED.getKey(),IsDeleteEnum.NO.getKey());
		return CollectionUtils.isNotEmpty(list);
	}

	@Override
	public SupplyPlanVersion selectNewestVersionByPriceId(String priceVersionId) {
		return supplyPlanVersionMapper.selectNewestVersionByPriceId(priceVersionId,IsDeleteEnum.NO.getKey());
	}

	@Override
	public boolean isNeedConfirmSupply(String projectId, String affiliationMonth) {
		boolean flag = false;
		List<SupplyPlanVersion> list = supplyPlanVersionMapper.selectNewestDynamicVersion(projectId,affiliationMonth,IsDeleteEnum.NO.getKey());
		for(SupplyPlanVersion version : list) {
			List<SupplyPlanVersionDetail> detailList = supplyPlanVersionDetailMapper.selectByVersionId(version.getId(), IsDeleteEnum.NO.getKey());
			for(SupplyPlanVersionDetail detail : detailList) {
				if(detail.getType().equals(OrgTypeEunm.ORG_BUILD.getKey())) {
					LocalDateTime supplyDateActual = detail.getSupplyDateActual() == null ? detail.getSupplyTimeVirtual() : detail.getSupplyDateActual();
					String bussinessType = detail.getBusinessType();
					if(bussinessType.equals(SalyTypeEnum.SALABLE.getKey()) || bussinessType.equals(SalyTypeEnum.STAGE_SELF_SUSTAINMENT.getKey()) ) {
						if(supplyDateActual == null) {
							flag = true;
							return flag;
						}
					}
				}
			}
		}
		return flag;
	}

	@Override
	public List<SupplyPlanVersionDetail> selectVersionDetailList(List<String> versionIds) {
		if(CollectionUtils.isNotEmpty(versionIds)) {
			return supplyPlanVersionDetailMapper.selectVersionDetailList(versionIds,IsDeleteEnum.NO.getKey());
		}
		return Collections.synchronizedList(new ArrayList<>());
	}

	@Override
	public void handleConfirmSupplyData(String month,String projectFid,String isSignFlag,String isAll) {
		if(StrUtils.isNotEmpty(isAll) && isAll.equals("0")) {
			SupplyPlanVersion finalize = supplyPlanVersionMapper.selectFinalize(month,projectFid,IsDeleteEnum.NO.getKey());
			SupplyPlanVersion confirm = supplyPlanVersionMapper.selectConfirm(month,projectFid,IsDeleteEnum.NO.getKey());
			if(finalize != null && confirm != null) {
				if(!finalize.getId().equals(confirm.getId())) {
					updateVersionData(finalize,confirm);
					supplyPlanVersionDetailMapper.updateVersion(confirm.getId(),2);
					List<SupplyPlanVersionDetail> fDetailList = supplyPlanVersionDetailMapper.selectByVersionId(finalize.getId(),IsDeleteEnum.NO.getKey());
					supplyPlanVersionDetailMapper.insertBatchTemp(fDetailList,confirm.getId());
				}
			}
		}else {
			List<SupplyPlanVersion> finalizeList = supplyPlanVersionMapper.selectFinalizeVersionList(month);
			List<SupplyPlanVersion> confirmList = supplyPlanVersionMapper.selectConfirmVersionList(month);
			for(SupplyPlanVersion confirm : confirmList) {
				String cStageId = confirm.getProjectfId();
				String cSourcePriceId = confirm.getSourcePriceId();
				String cVersionId = confirm.getId();
				//已被签约使用，不刷
				boolean isSign = signPlanVersionService.supplyBoolean(cVersionId);
				if(StrUtils.isNotEmpty(isSignFlag) && isSignFlag.equals("0")) {
					SupplyPlanVersion finalizeVersion = getFinalizeVersionId(cStageId,cSourcePriceId,finalizeList);
					if(finalizeVersion != null) {
						updateVersionData(finalizeVersion,confirm);
						supplyPlanVersionDetailMapper.updateVersion(cVersionId,2);
						List<SupplyPlanVersionDetail> fDetailList = supplyPlanVersionDetailMapper.selectByVersionId(finalizeVersion.getId(),IsDeleteEnum.NO.getKey());
						supplyPlanVersionDetailMapper.insertBatchTemp(fDetailList, cVersionId);
					}
				}else {
					if(!isSign) {
						SupplyPlanVersion finalizeVersion = getFinalizeVersionId(cStageId,cSourcePriceId,finalizeList);
						if(finalizeVersion != null) {
							updateVersionData(finalizeVersion,confirm);
							supplyPlanVersionDetailMapper.updateVersion(cVersionId,2);
							List<SupplyPlanVersionDetail> fDetailList = supplyPlanVersionDetailMapper.selectByVersionId(finalizeVersion.getId(),IsDeleteEnum.NO.getKey());
							supplyPlanVersionDetailMapper.insertBatchTemp(fDetailList, cVersionId);
						}
					}
				}
			}

		}
	}

	public SupplyPlanVersion getFinalizeVersionId(String cStageId,String cSourcePriceId,List<SupplyPlanVersion> finalizeList) {
		for(SupplyPlanVersion finalize : finalizeList ) {
			String fStageId = finalize.getProjectfId();
			String fSourcePriceId = finalize.getSourcePriceId();
			if(StrUtils.isNotEmpty(fStageId) && StrUtils.isNotEmpty(cStageId) && fStageId.equals(cStageId)) {
				if(StrUtils.isNotEmpty(cSourcePriceId) && StrUtils.isNotEmpty(fSourcePriceId) && !cSourcePriceId.equals(fSourcePriceId)) {
					return finalize;
				}
			}
		}
		return null;
	}

	private void updateVersionData(SupplyPlanVersion version, SupplyPlanVersion handleVersion) {
		handleVersion.setSourcePriceId(version.getSourcePriceId());
		handleVersion.setSourcePriceName(version.getSourcePriceName());
		handleVersion.setSourcePriceNum(version.getSourcePriceNum());
		handleVersion.setSourceBuildplanVersionId(version.getSourceBuildplanVersionId());
		handleVersion.setSourceBuildplanVersionName(version.getSourceBuildplanVersionName());
		supplyPlanVersionMapper.updateById(handleVersion);
	}

	@Override
	public List<ProjectByStages> selectProjectParentList() {
		return supplyPlanVersionMapper.selectProjectParentList();
	}

	@Override
	public List<Map<String, Object>> selectStageInfo(String stageId, String createTime) {
		return supplyPlanVersionMapper.selectStageInfo(stageId,createTime);
	}

	@Override
	public boolean isValidSupplyPlanVersion(String supplyPlanVersionId) {
		boolean isValid = false;
		if(StrUtils.isNotEmpty(supplyPlanVersionId)) {
			SupplyPlanVersion version = supplyPlanVersionMapper.selectOneByVersionId(supplyPlanVersionId,IsDeleteEnum.NO.getKey());
			if(version != null) {
				List<SupplyPlanVersionDetail> detailList = supplyPlanVersionDetailMapper.selectByVersionId(supplyPlanVersionId, IsDeleteEnum.NO.getKey());
				if(version.getVersionType().equals(VersionTypeEunm.INVESTMENT.getKey())) {
					for(SupplyPlanVersionDetail detail : detailList) {
						if(detail.getType().equals(OrgTypeEunm.ORG_PRODUCT.getKey())) {
							String businessTypeName = detail.getBusinessTypeName();
							if(StrUtils.isNotEmpty(businessTypeName)&& isValid(businessTypeName)) {
								return true;
							}
						}
					}
				}else {
					for(SupplyPlanVersionDetail detail : detailList) {
						if(detail.getType().equals(OrgTypeEunm.ORG_BUILD.getKey())) {
							String businessTypeName = detail.getBusinessTypeName();
							if(StrUtils.isNotEmpty(businessTypeName)&& isValid(businessTypeName)) {
								return true;
							}
						}
					}
				}
			}
		}
		return isValid;
	}

	private boolean isValid(String businessTypeName) {
		return businessTypeName.equals(SalyTypeEnum.SALABLE.getValue()) || businessTypeName.equals(SalyTypeEnum.STAGE_SELF_SUSTAINMENT.getValue());
	}

}
